const express = require('express');
const { stack } = require('../app');
const router = express.Router();
const timestamp = require('time-stamp');

let myQuery = require('../tools/db');
let { apiUrl, md5suo, jwtsuo } = require('../tools/config')
let toke = require('../tools/token');

//视频页
router.get('/info/:cid', async (req, res, next) => {
    let { cid } = req.params;
    //判断是否有cid
    if (!cid) {
        next({ code: 400, msg: '请传必要参数' });
    }
    //获取课程
    let sql = `SELECT id,cid,title,intro,grade_name,subject_name,area_name,price,category_name,tid FROM e_course WHERE cid='${cid}';`;
    let [err, result] = await myQuery(sql);
    if (err) {
        next({ code: 500, err });
    }

    //通过tid查找老师的信息
    let [{ tid }] = result;
    let sql1 = `SELECT id,tid,realname,intro,CONCAT('http://localhost:3000/uploads/','avatar/',head_photo_url) AS head_photo_url FROM e_teacher WHERE tid='${tid}';`;
    let [err1, result1] = await myQuery(sql1);
    if (err1) {
        next({ code: 500, err1 });
    }

    //通过cid获取视频
    let sql2 = `SELECT id,vnum,CONCAT('${apiUrl}','video/',video_src) AS video_src ,video_title FROM e_video WHERE cid='${cid}'`;
    let [err2, result2] = await myQuery(sql2);
    if (err2) {
        next({ code: 500, err2 });
    }
    //返回数据
    res.send({ node: 200, result: { course: result[0], thecher: result1[0], video: result2 } })
})



//验证token的中间件
router.use((req, res, next) => {
    let token = req.headers.authorization;
    let obj = toke.jwtVerify(token, jwtsuo);
    if (!obj) {
        next({ code: 200, msg: '请先登录' })
    }
    req.mid = obj.mid;
    next();
})



//报名
router.post('/study', async (req, res, next) => {
    
    let { cid } = req.body;

    if (!cid) {
        next({ code: 400, msg: '请传必要参数' });
        return;
    }
    //通过mid查看是否已经报名
    let sql = `SELECT * FROM e_order WHERE cid='${cid}' AND mid='${req.mid}'`;
    let [err, result] = await myQuery(sql);
    if (err) {
        next({ code: 500, err });
        return;
    }
    if (result.length > 0) {
        next({ code: 400, msg: '已报名' });
        return;
    }
    //报名
    let time = timestamp('YYYYMMDDHHmmss') + (Math.random() + '').slice(2, 10);
    let sql1 = `INSERT INTO e_order (oid,cid,mid,createdate) VALUES (${time},'${cid}','${req.mid}','${Date.now()}')`;
    let [err1, result1] = await myQuery(sql1);

    if (err1) {
        next({ code: 500, err1 });
        return;
    }
    if (result1.insertId > 0) {
        res.send({ code: 200, msg: '报名成功' })
    } else {
        next({ code: 500, msg: '请稍后再试' });
    }
})

//视频播放
router.get('/video', async (req, res, next) => {
    //获取视频的id
    let { id } = req.query;
    console.log(req.query);
    let sql = `SELECT id,cid,vnum,CONCAT('${apiUrl}','video/',video_src) AS video_src,video_title FROM e_video WHERE id=${id};`;
    let [err, result] = await myQuery(sql);
    if (err) {
        next({ code: 500, err });
    }
    res.send({ code: 200, result })
})

module.exports = router;